package com.gxuwz.stats.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.config.DateConfig;
import com.gxuwz.stats.entity.AcademicPapers;
import com.gxuwz.stats.entity.AcademicWork;
import com.gxuwz.stats.entity.ResearchProject;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.security.jwt.JwtTokenUtil;
import com.gxuwz.stats.service.AcademicWorkService;
import com.gxuwz.stats.service.UserService;
import com.gxuwz.stats.utils.ExcelExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/userAcademicWork")
public class AcademicWorkUserController {

    @Autowired
    private AcademicWorkService academicWorkService;
    @Autowired
    private UserService userService;

    /**
     * 分页查询
     * @param params
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/acaWoUserList")
    public ResponseEntity<Map<String, Object>> acaWoUserList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestHeader("Authorization") String authorization) {
        try {
            System.out.println("收到的查询集："+params);
            // 提取 Token
            String token = authorization.replace("Bearer ", "");

// 解析 Token 获取当前用户ID（假设使用 JWT）
            JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
            String userId = jwtTokenUtil.getUserIdFromToken(token); // 自定义工具类解析Token

            // 创建 MyBatis Plus 的 Page 对象进行分页查询
            IPage<AcademicWork> page = new Page<>(currentPage, pageSize);
            QueryWrapper<AcademicWork> queryWrapper = new QueryWrapper<>();

            // 添加当前用户ID条件
//            queryWrapper.eq("user_id", params.get("userId"));
// 强制添加当前用户ID条件
            queryWrapper.eq("user_id", userId);

//            // 模糊查询条件 - 项目名称
            if (params.containsKey("workName") && params.get("workName") != null && !params.get("workName").isEmpty()) {
                queryWrapper.like("work_name", params.get("workName"));
            }

            // 模糊查询条件 - 项目级别
            if (params.containsKey("academicWorkCategory") && params.get("academicWorkCategory") != null && !params.get("academicWorkCategory").isEmpty()) {
                queryWrapper.like("academic_work_category", params.get("academicWorkCategory"));
            }

            // 模糊查询条件 - 项目类别
            if (params.containsKey("isbn") && params.get("isbn") != null && !params.get("isbn").isEmpty()) {
                queryWrapper.like("isbn", params.get("isbn"));
            }

            // 精确查询条件 - 出版时间
            if (params.containsKey("publishDate") && params.get("publishDate") != null && !params.get("publishDate").isEmpty()) {
                queryWrapper.apply("YEAR(publish_date) = {0}", params.get("publishDate"));
            }

            // 模糊查询条件 - 出版社名称
            if (params.containsKey("publisher") && params.get("publisher") != null && !params.get("publisher").isEmpty()) {
                queryWrapper.like("publisher", params.get("publisher"));
            }

            // 精确查询条件 - 项目提交状态
            if (params.containsKey("academicStatus") && params.get("academicStatus") != null && !params.get("academicStatus").isEmpty()) {
                queryWrapper.eq("academic_status", params.get("academicStatus"));
            }

            // 精确查询条件 - 项目审核状态
            if (params.containsKey("reviewStatus") && params.get("reviewStatus") != null && !params.get("reviewStatus").isEmpty()) {
                queryWrapper.eq("review_status", params.get("reviewStatus"));
            }

            // 调用 service 层的分页查询方法
            IPage<AcademicWork> resultPage = academicWorkService.getAWListWithUserInfo(page, queryWrapper);
            // 构造返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords());
            response.put("total", resultPage.getTotal());
            response.put("currentPage", resultPage.getCurrent());
            response.put("pageSize", resultPage.getSize());
            response.put("totalPages", resultPage.getPages());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
    /**
     * 新增决策咨询数据
     */
    @PostMapping("/addAcademicWork")
    public ResponseEntity<Map<String, Object>> saveAcademicWork(@RequestBody AcademicWork academicWork) {
        System.out.println("前端数据：" + academicWork);

        // 创建响应 Map
        Map<String, Object> response = new HashMap<>();

        // 1. 验证 username 是否存在
        String username = academicWork.getUsername();
        if (username == null || username.isEmpty()) {
            response.put("code", 400);
            response.put("msg", "用户名不能为空");
            return ResponseEntity.badRequest().body(response);
        }

        // 2. 根据 username 查询 user_id
        String userId = userService.getUserIdByUsername(username);
        if (userId == null) {
            response.put("code", 400);
            response.put("msg", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }

        // 3. 设置 user_id
        academicWork.setUserId(userId);
        
        // 4. 自动计算分值
        int baseScore = academicWorkService.getScoreByType(academicWork.getAcademicWorkCategory());
        academicWork.setAcademicWorkScore(baseScore);

        // 5. 设置状态为未提交，提交时间为空
        academicWork.setAcademicStatus("未提交");
        academicWork.setReviewStatus("未审核");
        academicWork.setSubmissionTime(null);



        try {
            // 保存到数据库
            academicWorkService.save(academicWork);
            
            // 5. 计算并更新总分值
            double totalScore = academicWorkService.calculateTotalScore(academicWork);
            academicWork.setAcademicWorkTotalScore(totalScore);

            //6、总分值
            String year = null;
            if (academicWork.getPublishDate() != null) {
                try {
                    // 支持 "yyyy-MM" 或 "yyyy/MM" 或 "yyyy" 格式
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                    year = sdf.format(academicWork.getPublishDate());
                } catch (Exception e) {
                    // 如果格式不对，兜底取前4位
                    year = academicWork.getPublishDate().substring(0, 4);
                }
            }
            academicWorkService.updateTotalWorkAcademicScore(userId, year);

            // 返回成功响应
            response.put("code", 200);
            response.put("msg", "新增成功");
            return ResponseEntity.status(HttpStatus.CREATED).body(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("msg", "服务器内部错误");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 提交
     */
    @PostMapping("/submitAcademicWork")
    public ResponseEntity<Map<String, Object>> submitAcademicWork(@RequestBody Map<String, Object> params) {
        Map<String, Object> response = new HashMap<>();
        Long academicWorkId = Long.valueOf(params.get("academicWorkId").toString());
        AcademicWork academicWork = academicWorkService.getById(academicWorkId);
        if (academicWork == null) {
            response.put("code", 404);
            response.put("msg", "数据不存在");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
        }
        academicWork.setAcademicStatus("已提交");
        academicWork.setReviewStatus("未审核");
        academicWork.setReviewTime(null);
        academicWork.setSubmissionTime(LocalDateTime.now());
        academicWorkService.updateById(academicWork);
        response.put("code", 200);
        response.put("msg", "提交成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 撤回
     */
    @PostMapping("/revokeAcademicWork")
    public ResponseEntity<Map<String, Object>> revokeAcademicWork(@RequestBody Map<String, Object> params) {
        Map<String, Object> response = new HashMap<>();
        Long academicWorkId = Long.valueOf(params.get("academicWorkId").toString());
        AcademicWork academicWork = academicWorkService.getById(academicWorkId);
        if (academicWork == null) {
            response.put("code", 404);
            response.put("msg", "数据不存在");
            return ResponseEntity.ok(response);
        }
        // 只有审核通过/审核不通过不能撤回，其余都能撤回
        if ("审核通过".equals(academicWork.getReviewStatus()) || "审核不通过".equals(academicWork.getReviewStatus())) {
            response.put("code", 400);
            response.put("msg", "已审核，不可撤回");
            return ResponseEntity.ok(response);
        }
        academicWork.setAcademicStatus("未提交");
        academicWork.setSubmissionTime(null);
        academicWork.setReviewTime(null);
        academicWorkService.updateById(academicWork);
        response.put("code", 200);
        response.put("msg", "撤回成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 修改
     */
    @PutMapping("/updateAcademicWork")
    public ResponseEntity<Map<String, Object>> updateAcademicWork(
            @RequestBody AcademicWork academicWork
    ) {
        try {
            // 1. 自动计算分值
            int baseScore = academicWorkService.getScoreByType(academicWork.getAcademicWorkCategory());
            academicWork.setAcademicWorkScore(baseScore);
            
            // 2. 更新数据库
            academicWorkService.updateById(academicWork);
            
            // 3. 计算并更新总分值
            double totalScore = academicWorkService.calculateTotalScore(academicWork);
            academicWork.setAcademicWorkTotalScore(totalScore);

            //6、总分值
            String year = null;
            if (academicWork.getPublishDate() != null) {
                try {
                    // 支持 "yyyy-MM" 或 "yyyy/MM" 或 "yyyy" 格式
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                    year = sdf.format(academicWork.getPublishDate());
                } catch (Exception e) {
                    // 如果格式不对，兜底取前4位
                    year = academicWork.getPublishDate().substring(0, 4);
                }
            }
            academicWorkService.updateTotalWorkAcademicScore(academicWork.getUserId(), year);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "修改成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("msg", "修改失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 删除
     */
    @DeleteMapping("/delUserAcademicWork")
    public ResponseEntity<Map<String, Object>> deleteUserAcademicWork(@RequestBody List<Long> academicWorkIds) {
        System.out.println("删除：" + academicWorkIds);
        // 1. 查询所有被删的记录
        List<AcademicWork> worksToDelete = academicWorkService.listByIds(academicWorkIds);

        // 2. 删除
        academicWorkService.removeByIds(academicWorkIds);

        // 3. 对每个 userId+year 组合，更新总分
        Set<String> userYearSet = new HashSet<>();
        for (AcademicWork work : worksToDelete) {
            if (work.getUserId() != null && work.getPublishDate() != null) {
                String year = null;
                try {
                    // 支持 "yyyy-MM" 或 "yyyy/MM" 或 "yyyy" 格式
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                    year = sdf.format(work.getPublishDate());
                } catch (Exception e) {
                    // 如果格式不对，兜底取前4位
                    year = work.getPublishDate().substring(0, 4);
                }
                String key = work.getUserId() + "_" + year;
                if (!userYearSet.contains(key)) {
                    academicWorkService.updateTotalWorkAcademicScore(work.getUserId(), year);
                    userYearSet.add(key);
                }
            }
        }

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "删除成功");
        return ResponseEntity.ok(response);
    }

    @GetMapping("/export")
    public void exportAcademicWorks(
            @RequestParam(value = "year", required = false) String year,
            @RequestHeader("Authorization") String authorization,
            HttpServletResponse response) throws Exception {
        // 1. 解析token获取userId
        String token = authorization.replace("Bearer ", "");
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        String userId = jwtTokenUtil.getUserIdFromToken(token);

        // 2. 查找用户名
        User user = userService.getOne(new QueryWrapper<User>().eq("user_id", userId));
        String username = user != null ? user.getUsername() : "未知用户";

        // 3. 查询 AcademicWork（可按年份筛选）
        QueryWrapper<AcademicWork> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId); // 只查当前用户
        if (year != null && !year.isEmpty()) {
            queryWrapper.like("publish_date", year.substring(0, 4));
        }

        // 只导出审核通过的数据
//        queryWrapper.eq("review_status", "审核通过");

        List<AcademicWork> list = academicWorkService.list(queryWrapper);

        // 4. 查询所有用户，构建 userId -> username 映射
        List<User> userList = userService.list();
        Map<String, String> userIdNameMap = userList.stream()
                .collect(Collectors.toMap(User::getUserId, User::getUsername, (a, b) -> a));
        for (AcademicWork w : list) {
            w.setUsername(userIdNameMap.getOrDefault(w.getUserId(), ""));
        }

        // 5. 给每条数据加序号
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setRowNum(i + 1); // 从1开始
        }

        // 6. 生成文件名
        String now = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        String fileName = "学术著作-" + username + "-" + now + ".xlsx";
//        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

        // 7. 导出
        ExcelExportUtil.export(response, list, AcademicWork.class, "学术著作", fileName);
    }

}
